import logger from "morgan";
import { getStream } from "file-stream-rotator";

const { LOGGER_FILE, LOGGER_FILE_ERR } = process.env;

let accessLogStream = getStream({
   filename: LOGGER_FILE,
   frequency: "daily",
   verbose: false,
   date_format: "YYYY-MM-DD"
});

function formatLog(tokens: any, req: any, res: any) {
   return [
      tokens.method(req, res),
      tokens.url(req, res),
      tokens.status(req, res),
      decodeURI(tokens.url(req, res)), // 获取get参数
      JSON.stringify(req.body),
      tokens.res(req, res, "content-length"),
      "-",
      tokens["response-time"](req, res),
      "ms"
   ].join(" ");
}

const accessLog = logger((tokens, req, res) => formatLog(tokens, req, res), { stream: accessLogStream });

// 写入文件中 file-stream-rotator 错误日志
let accessLogStreamErr = getStream({
   filename: LOGGER_FILE_ERR,
   frequency: "daily",
   verbose: false,
   date_format: "YYYY-MM-DD"
});

const accessLogErr = logger((tokens, req, res) => formatLog(tokens, req, res), {
   stream: accessLogStreamErr,
   skip: (req, res) => res.statusCode < 400
});
// 导出代码
export default { accessLog, accessLogErr, logger };
